'use strict';
import cfg from '../config';
import qs from 'qs';

function handleUrl(url){
	if(path.indexOf('http://') > -1 || path.indexOf('https://') > -1){
        return path;
    }else{
        return cfg.domain + path;
    }
}

async function request(opt) {
	let {
		method='post',
		url,
		data={},
		header={}
	} = opt;
	let headers = new Headers();
	headers.append('Content-Type', 'application/x-www-form-urlencoded');
	Object.keys(header).forEach((key) => {
		headers.append(key,header[key]);
	})
	try{
		let result = await fetch(handleUrl(url),
						{
							method,
							headers,
							body:qs.stringify(data)
						})

	}catch(e){
		console.log('网络请求失败' + e);
	}
}

function post(opt){
	opt.method = 'post'
    return request(opt);
}

function get(opt){
	opt.method = 'get'
    return request(opt);
}

module.exports={post,get,request};